import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { CodeErrorModule } from './error.code';

/**
 * 捕捉error.code的错误
 */
@Catch(CodeErrorModule)
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger('Exception');
  // 捕捉CodeErrorModule的错
  catch(exception: CodeErrorModule, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    let message = request.body;
    const status = exception.getStatus(); // code
    const error = exception.getResponse(); // message
    this.logger.error(`Http Exception: ${JSON.stringify(error)}`);
    response.status(status).json({
      error: error,
      rid: message.mid,
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }

}
